package com.luyuan.crm.member.web;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.faces.model.DataModel;

import org.hibernate.criterion.Order;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.luyuan.crm.member.model.Member;
import com.luyuan.crm.member.model.MemberIntegralRecord;
import com.luyuan.crm.member.service.MemberIntegralRecordService;
import com.luyuan.crm.member.service.MemberService;
import com.ruijie.components.security.model.AppUser;
import com.ruijie.foundation.query.Page;
import com.ruijie.foundation.query.criteria.CriteriaTemplate;
import com.ruijie.foundation.query.criteria.RestrictionTemplate;
import com.ruijie.foundation.security.AppUserContext;
import com.ruijie.web.jsf.action.BaseAction;
import com.ruijie.web.jsf.context.TableContext;
import com.ruijie.web.jsf.model.PageDataModel;
import com.ruijie.web.jsf.model.TableOrder;
import com.ruijie.web.jsf.model.TablePage;

@Component("memberIntegralRecordAction")
@Scope("view")
public class MemberIntegralRecordAction extends BaseAction implements InitializingBean {

    @Resource(name = "memberService")
    private MemberService memberService;

    @Resource(name = "memberIntegralRecordService")
    private MemberIntegralRecordService memberIntegralRecordService;

    // 添加或编辑模型
    private Member member = null;

    public Member getMember() {
        return member;
    }

    public DataModel getTableModel() {
        CriteriaTemplate c = CriteriaTemplate.forClass(MemberIntegralRecord.class);
        TablePage tablePage = TableContext.getTablePage();
        if (tablePage == null) {
            return new PageDataModel(new Page());
        }
        List<TableOrder> tableOrders = TableContext.getTableOrders();
        List<Order> orders = new ArrayList<Order>();
        for (TableOrder tableOrder : tableOrders) {
            Order order = tableOrder.toOrder();
            if (order != null) {
                orders.add(order);
            }
        }
        RestrictionTemplate r = new RestrictionTemplate(false);
        c.add(r.eq("member", member));
        Page page = memberIntegralRecordService.pagedQuery(c, tablePage.getPage(), tablePage.getPageSize(), orders);
        return new PageDataModel(page);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        member = memberService.getByAccount((AppUser) AppUserContext.getCurrentUser());
    }
}
